﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.UI;
using Cms.Utilities;
using Cms.Web.Framework;

namespace Cms.Web.UI
{
    public partial class UrlSnapshot : Page
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (Common.GetCurrentTrustLevel() == TrustLevels.Unrestricted)
            {
                Response.ClearContent();
                Response.ClearHeaders();
                CreateSnapshotAndWriteToResponse();
                Response.End();
            }
            else
            {
                Response.Write("Url preview generation requires Full Trust.");
            }
        }

        private void CreateSnapshotAndWriteToResponse()
        {
            string url = Request.QueryString["url"];
            Size emulatedBrowserSize = new Size(1024, 768);
            int width = int.Parse(Request.QueryString["width"]);
            int height = int.Parse(Request.QueryString["height"]);
            Size thumbnailSize = new Size(width, height);
            var generator = new UrlSnapshotGenerator(url, emulatedBrowserSize, thumbnailSize);
            Bitmap bmp = generator.GetSnapshot();
            var ms = new MemoryStream();
            bmp.Save(ms, ImageFormat.Png);
            bmp.Dispose();
            generator.Dispose();
            Response.ContentType = "image/png";
            ms.WriteTo(Response.OutputStream);
            ms.Close();
            ms.Dispose();
        }
    }
}